#define DEBUG(x, s)	fprintf(stderr, "%s\t%d\n", s, x);

#include "Data.h"
#include "Controller.h"
#include "Menu.h"
#include "Game.h"
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>

update_time(Data* data){
	data->time.exec_time = SDL_GetTicks();
	switch(data->machine.pause.cur){
		case PAUSE:
			data->time.paused_time = data->time.exec_time - data->time.game_time;
			break;
		case PLAY:
			data->time.game_time = data->time.exec_time - data->time.paused_time;
			break;
	}
}

void update_main(Data* data, Control control){
	if(control.key_button == ESC){
		switch(data->machine.main.cur){
			case MENU : 
				data->machine.main.cur = GAME;
				break;
			default :
				data->machine.main.cur = MENU;
				break;
		}
	}
	update_time(data);
}

void liberate_proc(Data* data){
	if((data->time.exec_time - data->time.last_print) >= data->time.print){
		data->time.last_print = data->time.exec_time;
	} else 
		SDL_Delay(data->time.print - data->time.exec_time + data->time.last_print);
}

void Destroy(Data* data){
	DestroyData(data);
	SDL_Quit();
}

void display_main(Data* data){
	SDL_Flip(data->graphic.screen);
}

int main(int argc, char** argv){
	Data data;
	Rough rough;
	Control control;

	SDL_Init(SDL_INIT_VIDEO);
	InitData(&data, &rough);

	while(data.machine.main.cur != QUIT){
		getEvent(&control);

		update_main(&data, control);
		update_menu(&data, &rough, control);
		update_game(&data, control);

		display_game(&data);
		display_menu(&data);
		display_main(&data);
			
		liberate_proc(&data);
	}
	DestroyRough(&rough);
	Destroy(&data);
	return EXIT_SUCCESS;
}